<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="选择群" prop="groupId">
        <el-col :span="15">
          <el-form-item prop="groupId">
            <el-select v-model="queryParams.groupId" placeholder="请选择"
                       style="width: 180px" @change="handleQuery">
              <el-option
                  v-for="dict in userGroups"
                  :key="dict.id"
                  :label="dict.groupName"
                  :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="时间">
        <el-col :span="15">
          <el-date-picker
              v-model="queryParams.findTime"
              type="daterange"
              @change="handleQuery"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="文本内容" prop="txtContent">
        <el-input
            v-model="queryParams.txtContent"
            type="textarea"
            placeholder="文本内容"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">清空</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['group:impRecord:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['group:impRecord:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['group:impRecord:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['group:impRecord:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="群名称" align="center" prop="groupName"/>
      <el-table-column label="录入时间" align="center" prop="createTime" width="120px">
        <template #default="scope">
          {{ format(scope.row.createTime, 'yyyy-MM-dd') }}
        </template>
      </el-table-column>
      <el-table-column label="文本内容">
        <template #default="scope">
          <span style="white-space: pre-wrap;">{{ scope.row.txtContent }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否统计" align="center" prop="validStatus">
        <template #default="scope">
          <dict-tag :options="group_valid_status" :value="scope.row.validStatus"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="录入类型：0打水记录，1活动记录" align="center" prop="importType"/>-->
      <!--      <el-table-column label="租户编号" align="center" prop="tenantId"/>-->
      <!--      <el-table-column label="备注" align="center" prop="remark"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if="scope.row.validStatus === 1" link type="primary" icon="Link"
                     v-hasPermi="['group:boutStat:listPage']"
                     @click="skipPage(scope.row,'/group/boutStat')">打水统计
          </el-button>
          <el-button v-if="scope.row.validStatus === 1" link type="primary" icon="Link"
                     v-hasPermi="['group:boutRecord:listPage']"
                     @click="skipPage(scope.row,'/group/boutRecord')">单局详情
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-if="permitUpdate(scope.row.groupId)>0  && scope.row.validStatus===0"
                     v-hasPermi="['group:impRecord:update']">修改
          </el-button>
          <el-button link type="primary" icon="Edit" @click="detailF=true;handleUpdate(scope.row)"
                     v-if="permitUpdate(scope.row.groupId)>0  && scope.row.validStatus===1"
                     v-hasPermi="['group:impRecord:findDetail']">详情
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-if="permitUpdate(scope.row.groupId)>0"
                     v-hasPermi="['group:impRecord:deletes']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改录入记录:修改录入的时候要删掉单局和统计记录对话框 -->
    <el-dialog :title="title" v-model="open" width="580px" append-to-body :show-close="detailF"
               @closed="detailF=false;showParse=false,parseRes=[]">
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="选择群" prop="groupId">
          <el-col :span="12">
            <el-form-item prop="groupId">
              <el-select v-model="form.groupId" placeholder="请选择" :disabled="form.id>0 || queryParams.groupId>0">
                <el-option
                    v-for="dict in userGroups"
                    :key="dict.id"
                    :label="dict.groupName"
                    :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="文本内容">
          <el-button v-if="form.id" class="mgr-8" size="small" type="primary" @click="copy(form.txtContent)">复制
          </el-button>
          <el-input
              v-model="form.txtContent"
              style="width: 240px"
              type="textarea"
              :autosize="true"
              placeholder="Please input"
          />
        </el-form-item>
        <el-form-item label="统计状态" v-if="form.validStatus!==3">
          <el-radio-group v-model="form.validStatus">
            <el-radio
                v-for="dict in group_valid_status"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" v-if="!detailF">
          <el-button type="primary" @click="parseForm">解 析</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
      <div v-if="parseRes.length>0">
        <el-row>
          <el-col span="8">总和：{{ sum }} ;</el-col>
          <el-col span="8">正：{{ positive }}      </el-col>
          <el-col span="8">负：{{ passive }}       </el-col>
        </el-row>
        <el-table :data="parseRes">
          <el-table-column label="名称" align="center" prop="userGroupName"/>
          <el-table-column label="奖励" align="center" prop="awardCoin"/>
          <el-table-column label="总局" align="center" prop="totalBout"/>
          <el-table-column label="胜局" align="center" prop="winBout"/>
          <el-table-column label="负局" align="center" prop="loseBout"/>
          <el-table-column label="净胜" align="center" prop="totalScore"/>
        </el-table>
      </div>
      <el-button v-if="parseRes.length>0" class="mgr-8" size="small" type="primary" @click="copyRest()">复制</el-button>
    </el-dialog>
  </div>
</template>

<script setup name="Record">
import * as impServer from "@/api/group/impRecord.js";
import * as groupServer from "@/api/group/group.js";
import useClipboard from "vue-clipboard3";
import {AES_Decrypt, AES_Encrypt} from "@/utils/jsencrypt.js";
import {format} from "date-fns";

const {toClipboard} = useClipboard()

const {proxy} = getCurrentInstance();
const {group_valid_status} = proxy.useDict("group_valid_status");
const recordList = ref([]);
const parseRes = ref([]);
const positive = ref(0)
const passive = ref(0)
const sum = ref(0)
const showParse = ref(false);
const open = ref(false);
const detailF = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const router = useRouter();
const route = useRoute();
const groupId = ref(Number(AES_Decrypt(route.query.groupId)) === 0 ? undefined : Number(AES_Decrypt(route.query.groupId)));
const userGroupRefId = ref(Number(AES_Decrypt(route.query.userGroupRefId)) === 0 ? undefined : Number(AES_Decrypt(route.query.userGroupRefId)));
const userGroups = ref([])
const resetFlag = ref(false);
const groupPermitMap = reactive(new Map())

function skipPage(row, path) {
  router.push({path: path, query: {importId: AES_Encrypt(row.id), groupId: AES_Encrypt(row.groupId)}});
}

const copy = (text) => {
  toClipboard(text).then(() => {
    proxy.$modal.msgSuccess('复制成功');
  })
}
const copyRest = () => {
  let text = "";
  if (parseRes.value.length > 0) {
    parseRes.value.forEach(el => {
      text += el.userGroupName + ': ' + '\n' + `   奖励: ${el.awardCoin}, 净胜:${el.totalScore}, 胜:${el.winBout}, 负:${el.loseBout}` + '\n'
    })
    toClipboard(text).then(() => {
      proxy.$modal.msgSuccess('复制成功');
    })
  } else {
    proxy.$modal.msgSuccess('没有内容！');
  }
}

/** 获取用户所属群组 */
const data = reactive({
  form: {},
  queryParams: {
    startTime: null,
    findTime: null,
    endTime: null,
    orderByColumn: 'create_time desc,id',
    isAsc: 'desc',
    pageNum: 1,
    pageSize: 10,
    groupId: groupId.value,
    userGroupRefId: userGroupRefId.value,
    txtContent: null,
    validStatus: null,
    importType: null,
    tenantId: null,
  },
  rules: {
    groupId: [
      {required: true, message: "群id不能为空", trigger: "blur"}
    ],
    txtContent: [
      {required: true, message: "文本内容不能为空", trigger: "blur"}
    ],
    validStatus: [
      {required: false, message: "是否有效：0:无效，1:有效(导入统计)不能为空", trigger: "change"}
    ],
    importType: [
      {required: false, message: "录入类型：0打水记录，1活动记录不能为空", trigger: "change"}
    ],
    createTime: [
      {required: false, message: "创建时间不能为空", trigger: "blur"}
    ],
    updateTime: [
      {required: false, message: "更新时间不能为空", trigger: "blur"}
    ],
    deleted: [
      {required: false, message: "是否删除不能为空", trigger: "blur"}
    ],
    tenantId: [
      {required: false, message: "租户编号不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

const start = (() => {
  return new Promise(resolve => {
    groupServer.callFindList(null).then(res => {
      userGroups.value = res.data
      userGroups.value.forEach(item => {
        groupPermitMap.set(item.id, item.adminType)
      })
      if (!groupId.value && !resetFlag.value) {
        userGroups.value.forEach(item => {
          if (item.loginDefault === 1) {
            groupId.value = item.id
            queryParams.value.groupId = item.id
          }
        })
      }
      if (!groupId.value && !resetFlag.value) {
        groupId.value = userGroups.value[0].id
        queryParams.value.groupId = userGroups.value[0].id
      }
    }).then(() => {
      resolve()
    })
  })
})

function permitUpdate(groupId) {
  return groupPermitMap.get(groupId)
}

/** 查询录入记录:修改录入的时候要删掉单局和统计记录列表 */
function getList() {
  start().then(() => {
    loading.value = true;
    // if (queryParams.value.findTime) {
    //   queryParams.value.endTime = queryParams.value.findTime[1]
    //   queryParams.value.startTime = queryParams.value.findTime[0]
    // }
    impServer.listRecord(queryParams.value).then(response => {
      // //console.log(response.data.list);
      recordList.value = response.data.list;
      total.value = response.data.total;
      loading.value = false;
    });
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  parseRes.value = [];
  reset();
}

// 表单清空
function reset() {
  form.value = {
    startTime: null,
    findTime: null,
    endTime: null,
    id: null,
    groupId: null,
    userGroupRefId: null,
    txtContent: null,
    validStatus: 0,
    importType: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleted: null,
    tenantId: null,
    remark: null
  };

  proxy.resetForm("recordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 清空按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value = {
    startTime: null,
    findTime: null,
    endTime: null,
    orderByColumn: 'create_time,id',
    isAsc: 'desc',
    pageNum: 1,
    pageSize: 10,
    groupId: null,
    userGroupRefId: null,
    txtContent: null,
    validStatus: null,
    importType: null,
    tenantId: null,
  };
  resetFlag.value = true
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.groupId = queryParams.value.groupId;
  open.value = true;
  title.value = "添加录入记录:修改录入的时候要删掉单局和统计记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value[0]
  impServer.getRecord({id: _id}).then(response => {
    form.value = response.data;
    form.value.validStatus = response.data.validStatus === 1 ? 3 : 0;
    parseRes.value = response.data.boutStatVos;
    positive.value = 0
    passive.value = 0
    parseRes.value.forEach(e=>{
      if (e.awardCoin > 0) {
        positive.value=e.awardCoin + positive.value
      }else{
        passive.value=e.awardCoin + passive.value
      }
    })
    sum.value = passive.value+positive.value
    showParse.value = true;
    open.value = true;
    title.value = "修改录入记录:修改录入的时候要删掉单局和统计记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        impServer.updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        impServer.addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          parseRes.value = [];
          showParse.value = false;
          getList();
        });
      }
    }
  });
}

/** 解析按钮 */
function parseForm() {
  impServer.parseTxt({txtContent: form.value.txtContent, groupId: form.value.groupId}).then(response => {
    proxy.$modal.msgSuccess("解析成功");
    parseRes.value = response.data.boutStatVos;
    positive.value = 0
    passive.value = 0
    parseRes.value.forEach(e=>{
      if (e.awardCoin > 0) {
        positive.value=e.awardCoin + positive.value
      }else{
        passive.value=e.awardCoin + passive.value
      }
    })
    sum.value = passive.value+positive.value
    showParse.value = true;
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id ? [row.id] : ids.value;

  proxy.$modal.confirm('是否确认删除录入记录:修改录入的时候要删掉单局和统计记录编号为"' + _ids + '"的数据项？').then(function () {
    return impServer.delRecord({delIds: _ids});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('group/record/export', {
    ...queryParams.value
  }, `record_${new Date().getTime()}.xlsx`)
}

getList();
</script>
